package com.teamall.web.app.interceptor;

import com.teamall.framework.util.JsonUtil;
import com.teamall.framework.util.SpringAppContextUtil;
import com.teamall.framework.util.Utils;
import com.teamall.web.base.vo.ResResult;
import com.teamall.web.sys.db.po.SysUserPO;
import com.teamall.web.sys.db.po.SysUserTokenPO;
import com.teamall.web.sys.service.impl.SysUserServiceImpl;
import com.teamall.web.sys.service.impl.SysUserTokenServiceImpl;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author
 * @create 2017-07-28 23:20
 **/
public class AppInterceptor extends HandlerInterceptorAdapter {
    private List<String> excludedUrls;

    public List<String> getExcludedUrls() {
        return excludedUrls;
    }

    public void setExcludedUrls(List<String> excludedUrls) {
        this.excludedUrls = excludedUrls;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 排除在外的页面直接过去
        String requestUri = request.getRequestURI();
        for (String url : excludedUrls) {
            if (requestUri.indexOf(url)!=-1) {
                return true;
            }
        }
        String token = request.getHeader("token");
        if (Utils.isEmpty(token)) {
            System.out.println("token错误");
            ResResult resResult = new ResResult();
            resResult.setCode("8003");
            resResult.setMsg("你没有传入token");
            response.getWriter().write(JsonUtil.toJson(resResult));
            response.getWriter().close();
            return false;
        } else {
            SysUserTokenServiceImpl sysUserTokenService = SpringAppContextUtil.getBean(SysUserTokenServiceImpl.class);
            SysUserTokenPO sysUserTokenPO = sysUserTokenService.selectByToken(token);
            if(Utils.isEmpty(sysUserTokenPO)){
                ResResult resResult = new ResResult();
                resResult.setCode("8003");
                resResult.setMsg("你输入oken不存在");
                response.getWriter().write(JsonUtil.toJson(resResult));
                response.getWriter().close();
                return false;
            }else {
                request.setAttribute("userInfoId",sysUserTokenPO.getUserId());
                return true;
            }
        }
    }

}
